﻿/* BDVB-App
Copyright (C) 2014 Sascha Manns <Sascha.Manns@outlook.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/


using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Xml.Linq;

namespace AppStudio.Data
{
    internal class AtomReader : BaseRssReader
    {
        /// <summary>
        /// Atom reader implementation to parse Atom content.
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public override ObservableCollection<RssSchema> LoadFeed(XDocument doc)
        {
            try
            {
                var feed = new ObservableCollection<RssSchema>();

                if (doc.Root == null)
                    return feed;

                var items = doc.Root.Elements(doc.Root.GetDefaultNamespace() + "entry").Select(item => new RssSchema
                {
                    Title = item.GetSafeElementString("title").Trim(),
                    Summary = RssHelper.SanitizeString(Utility.DecodeHtml(GetItemSummary(item)).Trim().Truncate(500, true)),
                    Content = GetItemSummary(item),
                    ImageUrl = GetItemImage(item),
                    PublishDate = item.GetSafeElementDate("published"),
                    FeedUrl = item.GetLink("alternate"),
                }).ToList<RssSchema>();

                feed = new ObservableCollection<RssSchema>(items);

                return feed;
            }
            catch (Exception ex)
            {
                AppLogs.WriteError("AtomReader.LoadFeed", ex.Message);
                return null;
            }
        }

        private static string GetItemImage(XElement item)
        {
            if (!string.IsNullOrEmpty(item.GetSafeElementString("image")))
                return item.GetSafeElementString("image");

            return item.GetImage();
        }

        private static string GetItemSummary(XElement item)
        {
            var content = item.GetSafeElementString("description");
            if (string.IsNullOrEmpty(content))
            {
                content = item.GetSafeElementString("content");
            }
            if (string.IsNullOrEmpty(content))
            {
                content = item.GetSafeElementString("summary");
            }

            return content;
        }
    }
}
